import React, {Component} from 'react';

import {View, FlatList, ScrollView, TouchableOpacity, Text, Image, ListView, DeviceEventEmitter} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import I18n from "../../../res/language/i18n";
import ModalBottomUtils from "../../../utils/ModalBottomUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import ReturnGoodsOperation from "./ReturnGoodsOperation";


let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});


let ordersData = [];
export default class ReturnOrdersPage extends Component {


    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();

        this.commonUtils = new CommonUtils();
        this.modalDataSource = [I18n.t('default.all'), I18n.t('RT.exchangeGoods'), I18n.t('RT.exchangeRefund'), I18n.t('RT.refund')];
        this.state = {

            modalDialog: false,
            modalItemSelectIndex: 0,

            selectOrdersData: [],
        };
    }


    componentDidMount() {

        if (!this.props.currencyCode || !this.props.swap_amount) {
            CommonUtils.getAcyncInfo('getPv')
                .then((result) => {
                    let parse = JSON.parse(result);
                    this.swap_amount = parse.swap_amount;
                    this.currencyCode = parse.currency_code;

                });
        } else {
            this.swap_amount = this.props.swap_amount;
            this.currencyCode = this.props.currencyCode;
        }

        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                this.userInfo = JSON.parse(result);
                this.getOrdersData()
            });
    }


    /**
     * Get orders data
     */
    getOrdersData() {
        if (!this.userInfo) return;
        CommonUtils.showLoading();
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getReturn?', 'main_user_id=' + this.userInfo.main_user_id)
            .then((result) => {
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    ordersData = result.data;
                    this.setState({
                        selectOrdersData: result.data,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ReturnOrdersPage---getOrdersData--error:' + error);
            })
    }


    /*modalBottom list renderRow*/
    modalRow(rowData, sectionID, rowID) {
        return (<TouchableOpacity
                activeOpacity={0.5}
                onPress={() => {
                    let _orderData = [];


                    if (rowID != 0) {
                        for (orderItem of ordersData) {
                            if (orderItem.return_type == rowID) {
                                _orderData.push(orderItem);
                            }
                        }
                    } else {
                        _orderData = ordersData;
                    }

                    this.setState({
                        selectOrdersData: _orderData,
                        modalItemSelectIndex: rowID,
                        modalDialog: false,
                    })
                }}
                style={[StyleUtils.listItem, StyleUtils.center, StyleUtils.rowDirection]}>
                <Text
                    style={[StyleUtils.flex, StyleUtils.smallFont, {fontSize: 16, color: 'black'}]}>{rowData}</Text>
                <Image
                    source={this.state.modalItemSelectIndex == rowID ? require('../../../res/images/ic_selected_in.png')
                        : require('../../../res/images/ic_selected.png')}
                    style={{width: 18, height: 18}}/>
            </TouchableOpacity>
        )
    }

    render() {
        let state = this.state;
        return (
            <View style={[StyleUtils.flex]}>

                <Navigation onClickLeftBtn={() => this.props.navigator.popToTop()}/>

                <ScrollView>
                    <View style={{padding: 16}}>
                        {ViewUtils.getTitleView(I18n.t('RT.returnOrderList'), I18n.t('RT.returnGoodsPageMinContent'))}

                        {ViewUtils.getButtunMenu(I18n.t('default.selectOrderType'), () => {
                            this.setState({modalDialog: true})
                        })}

                        <View style={StyleUtils.lineStyle}/>
                        <View>
                            {/*//默认显示tabText*/}
                            {ViewUtils.getDefaultTab([I18n.t('default.orderNo'), I18n.t('default.amount'), I18n.t('default.status')], '', '', {height: 50}, StyleUtils.defaultTabTv)}
                        </View>


                        <FlatList
                            keyExtractor={(item, index) => index}
                            extraData={this.state}
                            renderItem={(index) => {
                                let dataRow = index.item;

                                let orderInfo = dataRow.order_info;

                                return ViewUtils.getDefaultTab(
                                    [orderInfo.order_sn, (dataRow.return_amount || 0).toFixed(2) + ' ' + this.currencyCode, this.commonUtils.orderStatus(dataRow.order_status, dataRow.return_type)],
                                    () => {
                                        this.props.navigator.push({
                                            component: ReturnGoodsOperation,
                                            name: 'ReturnGoodsOperation',
                                            params: {
                                                data: dataRow,
                                                userInfo: this.userInfo,
                                                ...this.props,
                                                swap_amount: this.swap_amount,
                                                currencyCode: this.currencyCode,
                                            }
                                        });
                                    }
                                )
                            }}
                            data={state.selectOrdersData}/>

                    </View>
                </ScrollView>


                <ModalBottomUtils
                    visible={state.modalDialog}
                    dataSource={ds.cloneWithRows(this.modalDataSource)}
                    requestClose={() => {
                        this.setState({
                            modalDialog: false,
                        });
                    }}
                    renderRow={this.modalRow.bind(this)}
                    title={I18n.t('default.selectOrderType')}
                />
            </View>
        );
    }

}
